package ar.com.photo_admin.domain

import java.util.Set;

class Event extends DomainObject {

	String name
	
	String description
	
	// Para ver donde almacena las fotos
	Integer number
	
	Date eventDate
	
	Set users
	
	List albums
	
	EventPhoto coverPhoto;
	
	List photos
	
	Photographer photographer
	
	User client
	
	boolean published

	static belongsTo = [client : User, photographer : Photographer]
		
	static hasMany = [albums : EventAlbum, photos : EventPhoto]

	static constraints = {
		name(blank:false,size:1..30)
		description(nullable:true,blank:true,size:0..200)
		coverPhoto(nullable:true)
		number(unique:true,nullable:false)
		photographer(nullable:false)
		eventDate(nullable:false)
		client(nullable:true)
	}
	
	static namedQueries = {
		ownedAsPhotographer { user ->
			eq('photographer', user)
		}
		
		ownedAsClient { user ->
			eq('client', user)
		}
		
		owned { user ->
			or {
				ownedAsPhotographer(user)
				ownedAsClient(user)
			}
		}
		
		canAccess { user ->
			def ids = user?.getAlbumsWhereCanAccess().collect { it.event.id }
			ids ? 'in'('id', ids) : idEq(-1L)
		}
		
		allEvents { user, q = "%" ->
			q = q?.trim() ? "%" + q + "%" : "%"
			
			if (!user.hasRole(Role.ROLE_ADMIN))
				and {
					or {
						owned(user)
						canAccess(user)
					}
					eq('deleted', false)
					like('name', q)
				}
			else
				like('name', q)
		}
	}
	
	def addPhoto(EventPhoto photo){
		photos.add(photo)
		photo.event = this
	}	
	
	def removePhoto(EventPhoto photo){
		photos.remove(photo);
		photo.event = null;
	}
	
	def removeAlbum(EventAlbum album){
		albums.remove(album);
		album.event = null;
	}
	
	boolean isOwner(User user) {
		return user == photographer || user == client
	}
}
